package com.fengxu.gamescript.ui.article

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.TextView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.util.CommonUtils
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import org.jetbrains.anko.sdk27.coroutines.onClick
import kotlin.properties.Delegates

@SuppressLint("JavascriptInterface")
// 文章界面
class ArticleActivity : BaseActivity() {

    // 提示加载的弹窗
    private var loadingDialog: MaterialDialog by Delegates.notNull()

    private val webView:WebView by lazy {
        findViewById(R.id.article_webview)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_article)
        initView()
    }

    /**
     * 初始化控件
     */
    private fun initView() {
        findViewById<View>(R.id.actionbar_back).onClick { finish() }
        findViewById<TextView>(R.id.actionbar_title).text = "文章"
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.addJavascriptInterface(this, "android")
        loadWebView(true)
    }

    /*
    * webView加载网页
    * @param 是否显示加载弹窗
    */
    private fun loadWebView(showLoading: Boolean = false){
        if(showLoading){
            loadingDialog = CommonUtils.loadingDialog(this)
        }
        webView.loadUrl("file:///android_asset/doc/index.html")
    }

    /**
     * 加载消息文档
     */
    @JavascriptInterface
    fun loadDoc():String{
        val bytes = assets.open("doc/msg.md").readBytes()
        return String(bytes)
    }

    /**
     * 加载完成
     */
    @JavascriptInterface
    fun loadComplete(){
        loadingDialog?.dismiss()
    }

}